import moment from 'moment';

export function numToFormat(str) {
  if (typeof str !== 'string') {
    str = str.toString();
  }
  const arr = str.split('.');
  const reg = /(?=(\B\d{3})+$)/g;
  arr[0] = arr[0].replace(reg, ',');
  return arr.join('.');
}

export function timeFormatHm(time) {
  return moment.unix(time).format('HH:mm');
}

export function timeFormatYMDHms(time) {
  return moment.unix(time).format('YYYY-MM-DD HH:mm:ss');
}

export function abbreviation(str, n = 11) {
  const len = str.length;
  if (len <= 2 * n) {
    return str;
  }
  const str1 = str.substring(0, n);
  const str2 = str.substring(len - n, len);
  return `${str1}......${str2}`;
}

export function getQueryVariable(variable) {
  const query = window.location.search.substring(1);
  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}

export function computeDay(sec) {
  let seconds = sec;
  if (typeof seconds === 'string') {
    seconds = parseInt(seconds);
  }
  const day = Math.floor(seconds / (60 * 60 * 24));
  const sec1 = seconds % (60 * 60 * 24);
  const hours = Math.floor(sec1 / (60 * 60));
  const sec2 = sec1 % (60 * 60);
  const minutes = Math.floor(sec2 / 60);
  seconds = sec2 % 60;
  return `${day}天${hours}时${minutes}分${seconds}秒`;
}

export function openWindow(url) {
  setTimeout(() => {
    const win = window.open('_blank');
    win.location.href = url;
  }, 500);
}
